package com.liancheng.smarthome.base;

import android.app.Activity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;

import com.httpapi.RxSubscriber;
import com.httpapi.apiservice.OnHttpApiListener;
import com.liancheng.smarthome.R;
import com.liancheng.smarthome.utils.common.ToastUtil;
import com.liancheng.smarthome.utils.ui.ForwardPopWindow;

/**
 * 与view搭配的viewmodel
 * <p>
 * 绑定网络请求回调
 */
public abstract class BaseFragmentVM<T extends BaseFragment> implements OnHttpApiListener {
    //请求对象，方便绑定到xml进行view启动请求
    protected T context;
    protected RxSubscriber subscriber;
    protected Activity activity;

    public BaseFragmentVM() {
    }

    /**
     * 绑定view
     *
     * @param context
     */
    public void bindViewAndModel(T context) {
        this.context = context;
        if (this.context != null) {
            this.activity = this.context.getActivity();
        }
//        model = MvpInstantiationUtils.getInstantiation(this, MvpInstantiationUtils.FIRSTGENERICITY);
//        model.setPresenter(this);
    }

    /**
     * 取消本类中设置的view引用
     */
    public void freeObject() {
        if (subscriber != null) {
            subscriber.dispose();
        }
        if (context != null) {
            context = null;
        }
    }

    //loading弹窗操作
    protected void showLoading() {
        if (context != null)
            context.showProcess();
    }

    protected void dissmissLoading() {
        if (context != null)
            context.dismissProcess();
    }

    /**
     * 请求异常提示
     */
    protected void showErrorMsg() {
        if (context == null) {
            return;
        }
        context.dismissProcess();
        context.closeRefresh();
        ToastUtil.showShort(activity, R.string.str_system_error);
    }

    /**
     * 提示请求失败的提示语:土司方式
     */
    public void showFailMsg(String msg) {
        if (context == null) {
            return;
        }
        context.dismissProcess();
        context.closeRefresh();
        if (TextUtils.isEmpty(msg)) {
            msg = context.getString(R.string.str_system_error);
        }
        ToastUtil.showLong(msg);
    }

    /**
     * 全屏的popwindow
     *
     * @return
     */
    protected ForwardPopWindow showMatchBottomPopWindow(View tagetView, View contentView
            , int width, int height) {
        ForwardPopWindow mPopWindow = new ForwardPopWindow.PopupWindowBuilder(activity).setView(contentView)
                //显示大小
                .size(width, height)
                //弹出popWindow时，背景是否变暗 这个属性设置后 ，会导致界面出现闪烁，不建议设置
                .setTouchable(true)
                .setOutsideTouchable(false)
                .create();
        mPopWindow.showAsDropDown(tagetView, 0, 0, Gravity.BOTTOM);
        return mPopWindow;
    }

}
